<script setup>
import { ref, watch } from 'vue';
import { workAddApi, updateWorkApi } from '@/apis/work.js'
import { useWorkStore } from '@/stores/workStore.js'
const workStore = useWorkStore()
//图片列表
const workInfo = ref({
    workId: "",
    workTitle: "",
    workContent: "",
    images: [],
    // 这个是拿来保存imgUrl
    indexImg: ""
})

const generateWorkId = () =>{
  const now = new Date();
  const y = now.getFullYear();
  const m = (now.getMonth() + 1).toString().padStart(2, '0');
  const d = now.getDate().toString().padStart(2, '0');
  const h = now.getHours().toString().padStart(2, '0');
  const i = now.getMinutes().toString().padStart(2, '0');
  const s = now.getSeconds().toString().padStart(2, '0');
  const ms = now.getMilliseconds().toString().padStart(3, '0');
  return `WK${y}${m}${d}${h}${i}${s}${ms}`;
}

const show = ref(false)
// 上传图片
const uploadImg = () => {
    uni.chooseImage({
        count: 9, // 默认9，设置图片选择的最大数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], // 从相册选择
        success: (res) => {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            //   拼接数组
            workInfo.value.images = [...workInfo.value.images, ...res.tempFilePaths];
        },
        fail: (err) => {
            // 用户取消选择或发生错误时执行的回调函数
            console.error(err);
            uni.showToast({
                title: '选择图片失败',
                icon: 'none'
            });
        }
    });
}
//反馈,图片放大预览
const handlePrevewImage = (e) => {
    //先构造要预览的图标数组
    const urls = workInfo.value.images;
    //接收传递过来的图片url
    const current = e;
    wx.previewImage({
        current, // 当前显示图片的http链接
        urls // 需要预览的图片http链接数组列表
    })

}

//删除data里面图片的方法
const bandleRemoveImg = (index) => {
    //2.获取data中的图片数组
    const imagesData = workInfo.value.images;
    //3.根据索引删除元素
    imagesData.splice(index, 1);
    //4.重新填充会images中
    workInfo.value.images = imagesData;
}
// 创建一个深度监听器来监听 images 的变化
watch(() => workInfo.value.images.length, (newVal, oldVal) => {
    if (newVal > 0) {
        show.value = true
    } else {
        show.value = false
    }
}, {
    deep: true // 设置 deep 为 true 来深度监听数组或对象内部的变化
});

const takeWork = async () => {
    if (workInfo.value.workContent === undefined || workInfo.value.workContent === '' || workInfo.value.workTitle === undefined || workInfo.value.workTitle === '') {
        uni.showToast({
            title: '请输入标题或内容',
            icon: 'none'
        });
    }
    const workId = generateWorkId()
    workInfo.value.workId = workId
    if (workInfo.value.images.length > 0) {
        // 添加作品
        // 进行发布调用后端接口
        for (let i = 0; i < workInfo.value.images.length; i++) {
            const imgRes = await uni.uploadFile({
                url: `http://localhost:6060/work/upload/${workId}`,
                filePath: workInfo.value.images[i],
                name: 'file',
                header: { 'token': uni.getStorageSync('token') },
            });
            if (i === 0) {
                workInfo.value.indexImg = JSON.parse(imgRes.data).imgUrl
            }
        }
        const workRes = await workAddApi(workInfo.value)
        if (workRes.code === 200) {
            // 重置表单数据
            reset()
            uni.showToast({
                title: '发布成功',
                icon: 'success',
                duration: 1000,
            });
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/index/index'
                })
            }, 1010);
        }
    }
    else {
        uni.showToast({
            title: '请添加至少一张图片',
            icon: 'none'
        });
    }


}

const reset = () => {
    workInfo.value = {
        workTitle: "",
        workContent: "",
        images: [],
        indexImg: ""
    }
}

</script>

<template>
    <view class="publish">
        <view class="main_body">
            <view class="character">
                <input v-model="workInfo.workTitle" type="text" placeholder="请输入作品标题(15个字以内)">
            </view>
            <view class="textarea">
                <textarea v-model="workInfo.workContent" placeholder="更多介绍"></textarea>
            </view>
            <!-- 图片上传 -->
            <view class="Upload_module">
                <view class="layout">
                    <view class="picture_list">
                        <!-- 图片 -->
                        <view v-for="(item, index) in workInfo.images" :key="index">
                            <view @tap="handlePrevewImage(item)" class="cu-avatar view"
                                :style="{ 'backgroundImage': 'url(' + item + ')' }">
                                <view class="cover" v-if="index === 0">封面</view>
                            </view>
                            <image class="delete" @tap="bandleRemoveImg(index)" mode="widthFix"
                                src="@/static/images/delete.png"></image>
                        </view>

                        <!-- 上传按钮 -->
                        <view class="uploadImg" @click="uploadImg">
                            <view class="image">
                                <image src="@/static/images/upload.png" mode="widthFix">
                                </image>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

        </view>

        <!-- <view style="height: 150rpx;"></view> -->
        <view class="btn_bottom">
            <button v-if="show" class="cu-btn bnt1" @click="takeWork()">确认发布</button>
            <button v-else class="cu-btn bnt2" @click="takeWork()">确认发布</button>
        </view>
    </view>
</template>

<style lang="scss" scoped>
.cu-avatar {
    font-variant: small-caps;
    margin: 0;
    padding: 0;
    display: inline-flex;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #ccc;
    color: #ffffff;
    white-space: nowrap;
    position: relative;
    width: 64upx;
    height: 64upx;
    background-size: cover;
    background-position: center;
    vertical-align: middle;
    font-size: 1.5em;
}

// 
.publish {
    height: 100%;
    background: #fafbfb;

    .main_body {
        margin-top: 24rpx;
        padding: 24rpx;
        border-top-left-radius: 24rpx;
        border-top-right-radius: 24rpx;
        background-color: #ffffff;

        .character {
            border-bottom: 2rpx solid #e8e8e8;
            padding: 22rpx 0;
        }

        .textarea {
            padding: 22rpx 0;
            border-bottom: 2rpx solid #e8e8e8;

            textarea {
                width: 100%;
                font-size: 28rpx;
            }
        }
    }


    .picture_list {
        display: flex;
        flex-wrap: wrap;

        .delete {
            position: absolute;
            right: 5px;
            z-index: 10;
            top: 5px;
            width: 16px;
            height: 16px;
            border-radius: 2px;
        }

        view {
            width: 154rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            height: 154rpx;
            position: relative;

            .cover {
                position: absolute;
                height: 44rpx;
                line-height: 44rpx;
                background: rgba(0, 0, 0, 0.4);
                bottom: 0;
                left: 0;
                font-size: 24rpx;
                margin: 0 !important;
                border-bottom-left-radius: 12rpx;
                border-bottom-right-radius: 12rpx;
            }

            image,
            .view {
                width: 154rpx;
                height: 154rpx;
                border-radius: 12rpx;
            }
        }
    }

    .delete_img {
        position: absolute;
        right: 10rpx;
        z-index: 10;
        top: 10rpx;
        width: 32rpx;
        height: 32rpx;
        border-radius: 4rpx;
    }

    .Upload_module {
        margin-top: 40rpx;

        .uploadImg {
            width: 150rpx;
            height: 150rpx;
            border: 2rpx solid #dfdfdf;
            border-radius: 12rpx;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;

            .image {
                display: flex;
                justify-content: center;
                align-items: center;

                image {
                    margin-left: 16rpx;
                    margin-top: 20rpx;
                    width: 60rpx;
                    height: 60rpx;
                }
            }
        }

        .layout {
            display: flex;
            align-items: center;
        }
    }



    .btn_bottom {
        height: 160rpx;
        padding: 12rpx 32rpx;
        background-color: #fafbfb;
        margin-top: 100rpx;

        .bnt1 {
            width: 100%;
            color: #fff;
            background: #4d5eff;
            height: 88rpx;
            line-height: 88rpx;
        }

        .bnt2 {
            width: 100%;
            color: #a4a4b0;
            background: #e9eafb;
            height: 88rpx;
            line-height: 88rpx;
        }
    }


}
</style>